package com.df.managers.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;

import com.df.managers.AbstractManager;
import com.df.managers.NewsManager;
import com.df.news.News;
import com.df.page.PagerModel;
@Service("newsManager")
public class NewsManagerImpl extends AbstractManager implements NewsManager {
	@Resource
	public void setSessionF(SessionFactory sessionFactory){
    	super.setSessionFactory(sessionFactory);
    }
	
	public void add(News news) {
		// TODO Auto-generated method stub
		String content = news.getContent();
		if(content.contains("<img")){
			if(content.contains("<img")){
				String subStr = content.substring(content.indexOf("<img"),content.indexOf("/>"));
				if(subStr.contains("src=")){
					subStr = subStr.substring(subStr.indexOf("src=")+5, subStr.lastIndexOf("\""));
					news.setImg(subStr);
				}
			}
		}
		getHibernateTemplate().saveOrUpdate(news);
	}

	public PagerModel list(int  id) {
		// TODO Auto-generated method stub
//		Query q = getHibernateTemplate().getSessionFactory().openSession().createQuery("from News");  
//		q.setFirstResult(20000);
//		q.setMaxResults(15);  
//		List l = q.list();
		
		if(id == 0){
			return  super.searchPaginated("from News n", " order by n.id");
		}
		return  super.searchPaginated("from News n where n.type.id = "+id, " order by n.id");
		
		//return getHibernateTemplate().find("from News");
	}

	public News getById(int id) {
		// TODO Auto-generated method stub
		return getHibernateTemplate().get(News.class, id);
	}

	public void update(News news) {
		// TODO Auto-generated method stub
		getHibernateTemplate().update(news);
	}

	public void del(int id) {
		// TODO Auto-generated method stub
		getHibernateTemplate().delete(getById(id));
	}

	public List<News> findByTypeAndCount(String showName, int count) {
		// TODO Auto-generated method stub
		if(showName != null && showName != ""){
			Query query = this.getSession().createQuery("from News n where n.type.showName = '"+showName+"'");
			 query.setMaxResults(count);
			return query.list();
		}
		return null;
		 
	}

	public News findByShowName(String showName) {
		if(showName != null && showName != ""){
			Query query = this.getSession().createQuery("from News n where n.showName = '"+showName+"'");
			return (News) query.uniqueResult();
		}
		return null;
		 
	}

	public PagerModel list(String showName) {
		
		return  super.searchPaginated("from News n where n.type.showName = '"+showName+"'", " order by n.id");
		
	}

}
